<template>
  <div class="row">
    <div class="col-md-4">
      <select class="form-control" :readonly="!isEditable" v-model="editBirthplace.province" @change="provinceChanged">
        <option :key='option.code' v-for="option in this.provinces" v-bind:value="option.code">{{ option.name }}</option>
      </select>
    </div>
    <div class="col-md-4">
      <select class="form-control" :readonly="!isEditable" v-model="editBirthplace.city">
        <option :key='option.code' v-for="option in this.selectcities" v-bind:value="option.code">{{ option.name }}</option>
      </select>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Birthplace',
    props: ['birthplace', 'withUnlimit','editable'],
    components: {
      // VueResource
    },
    data: function() {
      return {
        isEditable:true,
        editBirthplace: {
          province: '110000',
          city: '110100'
        },
        provinces: [],
        totalcities: [],
        selectcities: [],
      }
    },
    methods: {
      loaddata: function() {
        if (this.withUnlimit) {
          this.provinces = [{
            code: -1,
            name: '不限'
          }]
          this.provinces = this.provinces.concat(this.$store.state.provinces)
        } else
        this.provinces = this.$store.state.provinces
        this.totalcities = this.$store.state.cities
        this.selectcities = this.getcities(this.editBirthplace.province)
        this.editBirthplace.city = this.selectcities[0].code
      },
      getcities: function(code) {
        var cities = []
        if (this.withUnlimit) {
          cities.push({
            code: -1,
            name: '不限'
          })
        }
        this.totalcities.forEach(function(element) {
          if (element.parent_code == code) {
            cities.push(element)
          }
        }, this)
        return cities
      },
      provinceChanged: function(ele) {
        this.selectcities = this.getcities(this.editBirthplace.province)
        this.editBirthplace.city = this.selectcities[0].code
      }
    },
    created: function() {
      this.loaddata()
      if (this.editable != null && this.editable != undefined) {
        this.isEditable = this.editable
      }
      if (this.birthplace) {
        this.editBirthplace = this.birthplace
        this.selectcities = this.getcities(this.editBirthplace.province)
        this.editBirthplace.city = this.birthplace.city
      }
    }
  }
</script>
